package servlets;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class ConsultationRecordServlet extends BaseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static final String ADD_RECORD = "add-record";
	private static final String OPEN_RECORD = "open-record";

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	private void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String mode = (String) request.getParameter("request");

		Map<String, Object> data = new HashMap<String, Object>();

		if (mode.equals(ADD_RECORD)) {
			String complaints = request.getParameter("complaints");
			String diagnosis = request.getParameter("diagnosis");
			String prescription = request.getParameter("prescription");
			Float price = Float.parseFloat("" + request.getParameter("price"));
			Integer patientId = Integer.parseInt(""
					+ request.getParameter("patientId"));
			Integer staffId = 1;

			ConsultationRecord c = PatientManager
					.getInstance()
					.createConsultationRecord(complaints, diagnosis,
							prescription, patientId, staffId, price, new Date());

			if (c != null) {
				data.put("recordId", c.getConsultationRecordId());
				data.put("complaints", c.getComplaints());
				data.put("staff", "Linda Chua");
			}
		} else if (mode.equals(OPEN_RECORD)) {
			Integer recordId = Integer.parseInt(""
					+ request.getParameter("recordId"));

			ConsultationRecord r = PatientManager.getInstance()
					.getConsultationRecord(recordId);

			if (r != null) {
				data.put("complaints", r.getComplaints());
				data.put("diagnosis", r.getDiagnosis());
				data.put("prescription", r.getPrescription());
				data.put("staff", r.getStaffId());
				data.put("date", r.getDate());
				data.put("price", r.getPrice());
			}
		}

		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(new Gson().toJson(data));
	}
}
